package jobserver

import (
	"fmt"
	"gitee.com/scottq/go-framework/src/v1/log"
	"sync"
)

//JobRunner,负责并发处理某个任务
type JobRunner struct {
	name string
	sync.WaitGroup
	tasks []IJob

	log.InvokeLog
}

func NewJobRunner(name string) *JobRunner {
	return &JobRunner{
		name:  name,
		tasks: []IJob{},
	}
}

func (rn *JobRunner) Name() string {
	return rn.name
}

func (rn *JobRunner) AddJob(j IJob) {
	rn.tasks = append(rn.tasks, j)
}

func (rn *JobRunner) AddExecute(name string, f func()) {
	j := NewJob(name, f)
	rn.tasks = append(rn.tasks, j)
}

func (rn *JobRunner) Run()error {
	for i := 0; i < len(rn.tasks); i++ {
		rn.Add(1)
		go rn.run(rn.tasks[i])
	}
	rn.Wait()
	rn.Info(fmt.Sprintf("jobRunner[%s] run end", rn.Name()))
	return nil
}

func (rn *JobRunner) run(j IJob) {
	j.Run()
	rn.Done()
}

func (rn *JobRunner) Stop() error {
	return nil
}
